<?php
// 配置文件
define('TODO_FILE', 'todos.json');
define('UPLOAD_DIR', 'upload/');

// 初始化目录
if (!file_exists(UPLOAD_DIR)) {
    mkdir(UPLOAD_DIR, 0755, true);
}

// 读取现有数据
$todos = [];
if (file_exists(TODO_FILE)) {
    $todos = json_decode(file_get_contents(TODO_FILE), true) ?: [];
}

// 处理表单提交
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // 处理待办事项输入（包括图片上传的情况）
    $hasContent = !empty($_POST['content']);
    $hasImages = !empty($_FILES['images']) && count(array_filter($_FILES['images']['error'], function($error) {
        return $error === UPLOAD_ERR_OK;
    })) > 0;

    if ($hasContent || $hasImages) {
        // 生成待办事项内容
        if ($hasContent) {
            $newTodos = array_filter(
                array_map('trim', explode("\n", $_POST['content'])),
                function($line) { return $line !== ''; }
            );
        } else {
            // 没有输入内容但有图片时，自动填充"作业图片"
            $successImages = array_filter($_FILES['images']['error'], function($error) {
                return $error === UPLOAD_ERR_OK;
            });
            $imageCount = count($successImages);
            $newTodos = array_fill(0, $imageCount, '作业图片');
        }
        
        // 处理文件上传
        $images = [];
        if (!empty($_FILES['images'])) {
            foreach ($_FILES['images']['tmp_name'] as $key => $tmp_name) {
                if ($_FILES['images']['error'][$key] === UPLOAD_ERR_OK) {
                    $filename = uniqid() . '_' . basename($_FILES['images']['name'][$key]);
                    move_uploaded_file($tmp_name, UPLOAD_DIR . $filename);
                    $images[] = $filename;
                }
            }
        }

        // 添加新条目（倒序处理）
        $date = date('Y-m-d');
        $newTodos = array_reverse($newTodos);
        foreach ($newTodos as $index => $content) {
            $todos[] = [
                'status' => 0,
                'date' => $date,
                'content' => $content,
                'image' => $images[$index] ?? ''
            ];
        }
        
        // 保存数据
        file_put_contents(TODO_FILE, json_encode($todos, JSON_PRETTY_PRINT));
    }
    header('Location: index.php');
    exit;
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>新增作业</title>
    <style>
        body { font-family: sans-serif; padding: 20px; }
        h1 { font-size: 2em; margin-bottom: 20px; }
        textarea { 
            width: 100%;
            padding: 10px;
            font-size: 1.5em;
            margin-bottom: 10px;
        }
        button { 
            padding: 10px 20px; 
            font-size: 1em;
            background: #4CAF50;
            color: white;
            border: none;
            cursor: pointer;
            margin: 5px 0;
        }
    .timer-btn {
        padding: 12px 24px;
        font-size: 1em;
        background: #4CAF50;
        color: white;
        border: none;
        border-radius: 5px;
        cursor: pointer;
        transition: all 0.3s ease;
        box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        display: inline-block;
        /* 适配input文件选择按钮 */
        vertical-align: middle;
        -webkit-appearance: none;
        appearance: none;
    }
    .timer-btn:hover {
        transform: translateY(-2px);
        box-shadow: 0 6px 8px rgba(0,0,0,0.15);
    }
    .timer-btn:active {
        transform: translateY(0);
    }
    .button-container {
        display: flex;
        gap: 10px;
        flex-wrap: wrap;
        margin-bottom: 25px;
    }
        a { 
            display: inline-block;
            margin-top: 20px;
            color: #333;
            text-decoration: none;
            font-size: 1.2em;
        }
    </style>
</head>
<body>
    <h1>新增作业</h1>
    <div class="button-container">
        <a href="index.php" class="timer-btn">返回首页</a>
    </div>
    <form method="post" enctype="multipart/form-data">
        <textarea name="content" rows="5" placeholder="输入作业内容（每行一个）"></textarea><br>
        <div class="file-upload">
            <input type="file" name="images[]" multiple accept="image/*" id="fileInput" style="display: none;">
            <button type="button" class="timer-btn" onclick="document.getElementById('fileInput').click()">选择文件</button>
            <span id="fileNames" style="margin-left: 10px;"></span>
        </div>
        <script>
            document.getElementById('fileInput').addEventListener('change', function(e) {
                var fileNames = Array.from(e.target.files).map(file => file.name).join(', ');
                document.getElementById('fileNames').textContent = '已选择文件：' + fileNames;
            });
        </script>
        <div class="button-container">
            <button type="submit" class="timer-btn">提交作业</button>
        </div>
</body>
</html>